package tools

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/valyala/fasthttp"
	"net/url"
)

// 发送 HTTP 请求，并将返回的 JSON 数据解析到结构体中
func sendRequest(method, url string, headers map[string]string, responseData interface{}, body ...[]byte) error {
	fullURL := url
	req := fasthttp.AcquireRequest()
	defer fasthttp.ReleaseRequest(req)

	req.SetRequestURI(fullURL)
	req.Header.SetMethod(method)

	// 设置请求头
	for key, value := range headers {
		req.Header.Set(key, value)
	}

	if len(body) > 0 {
		req.SetBody(body[0])
	}

	resp := fasthttp.AcquireResponse()
	defer fasthttp.ReleaseResponse(resp)

	err := fasthttp.Do(req, resp)
	if err != nil {
		return err
	}
	if resp.StatusCode() != fasthttp.StatusOK {
		return fmt.Errorf("%s request failed with status: %d", method, resp.StatusCode())
	}

	err = json.Unmarshal(resp.Body(), responseData)
	if err != nil {
		return fmt.Errorf("failed to unmarshal %s response: %v", method, err)
	}

	return nil
}

// Get GetAPI 发起 GET 请求
func Get(url string, params url.Values, responseData interface{}) error {
	fullURL := url
	if len(params) > 0 {
		fullURL += "?" + params.Encode()
	}
	return sendRequest("GET", fullURL, nil, responseData)
}

// Post PostAPI 发起 POST 请求
func Post(url string, headers map[string]string, body []byte, responseData interface{}) error {
	return sendRequest("POST", url, headers, responseData, body)
}

// GetClientIP 获取客户端ip
func GetClientIP(c *gin.Context) string {
	ip := c.ClientIP()
	if ip == "::1" {
		ip = "127.0.0.1"
	}

	return ip
}
